#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>

using namespace std;

void solve() 
{
    int n;
    cin >> n;
    vector<char> s(n);
    for (int i = 0; i < n; i++)
    {
        cin >> s[i];
    }
    vector<char> temp = s;
    sort(temp.begin(), temp.end());
    if (s == temp)
    {
        cout << 0 << endl;
        return;
    }
    vector<int> indexs;
    char maxChar = 'a';
    string maxLexStr;
    map<char, int> Cmap;
    for (int i = n - 1; i >= 0; --i) 
    {
        if (s[i] >= maxChar) 
        {
            maxChar = s[i];
            maxLexStr += maxChar;
            indexs.push_back(i);
            Cmap[maxChar]++;
        }
    }
    int len = maxLexStr.length();
    bool flag = true;
    temp = s;
    for (int i =  0; i < len; i++)
    {
        temp[indexs[i]] = maxLexStr[i];
    }
    sort(s.begin(), s.end());
    if (s != temp)
    {
        cout << -1<<endl;
        return;
    }
    for (auto x : Cmap)
    {
        len -= x.second - 1;
    }
    cout << len - 1 << endl;
}

int main() 
{
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

    int t;
    cin >> t;

    while (t--) 
    {
        solve();
    }

    return 0;
}
